package com.example.yls.cnbetaapp.component;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.ViewTreeObserver;
import android.widget.TextView;


public class OnTvGlogbalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
    private TextView mText;
    public OnTvGlogbalLayoutListener(TextView view){
        this.mText = view;
    }
    @Override
    public void onGlobalLayout() {
        mText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        String newText = autoSplitText(mText);
        if (!TextUtils.isEmpty(newText)) {
            mText.setText(newText);
        }
    }
    public String autoSplitText(final TextView tv) {
        final String rawText = tv.getText().toString(); //原始文本
        final Paint tvPaint = tv.getPaint(); //paint，包含字体等信息
        final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度

        //将原始文本按行拆分
        String rawTextLine = rawText.replaceAll("\r\n","");
        StringBuilder sbNewText = new StringBuilder();
        float lineWidth = 0;
        for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
            char ch = rawTextLine.charAt(cnt);
            lineWidth += tvPaint.measureText(String.valueOf(ch));
            if (lineWidth <= tvWidth) {
                sbNewText.append(ch);
            } else {
                sbNewText.append("\n");
                lineWidth = 0;
                --cnt;
            }
        }
        return sbNewText.toString();
    }
}
